package com.doeis.uwork.module;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import com.alibaba.fastjson.JSON;
import com.doeis.common.utils.StringUtils;
import com.doeis.jpush.DoeisJPush;
import com.doeis.jpush.DoeisJPushWithAlias;
import com.doeis.jpush.JpushBean;
import com.doeis.log.QueueManager;
import com.doeis.minaserver.NettyServer;
import com.doeis.minaserver.container.BasicModule;
import com.doeis.minaserver.dao.User;
import com.doeis.minaserver.dao.UserDao;
import com.doeis.minaserver.module.ClientConnectionManager;
import com.doeis.minaserver.packet.ServerPacketFactory;
import com.doeis.minaserver.session.ClientConnection;
import com.doeis.uwork.bean.CacheBean;
import com.doeis.uwork.bean.ItemAttrs;
import com.doeis.uwork.common.Constant;
import com.doeis.uwork.common.PacketUtil;
import com.doeis.uwork.dao.ItemDao;
import com.doeis.uwork.dao.ItemNotesDao;
import com.doeis.uwork.dao.OffPacketMongoDao;
import com.doeis.uwork.dao.ShareDao;
import com.doeis.uwork.entity.Item;
import com.doeis.uwork.entity.ItemNoteComment;
import com.doeis.uwork.entity.ItemNotePraise;
import com.doeis.uwork.entity.ItemNotes;
import com.doeis.uwork.entity.Share;
import com.doeis.uwork.packet.GroupMsgPacket;
import com.doeis.uwork.packet.SystemPacket;
import com.voland.core.cache.CacheManager;


public class SystemPacketRouter extends BasicModule {

//	private static final Logger log = Logger.getLogger(SystemPacketRouter.class);
	private ItemDao itemDao;
	private ItemNotesDao itemNotesDao;
	private ShareDao shareDao;
	private UserDao userDao;
	private ClientConnectionManager clientConnectionManager = null;
	private OffPacketMongoDao offPacketMongoDao;
	
	public SystemPacketRouter() {
		super("system Message Router");
	}
	
	public SystemPacketRouter(String moduleName) {
		super(moduleName);
	}

	@Override
	public void initialize(NettyServer server) {
		this.server = server;		
		
		itemNotesDao= server.getItemNotesDao();
		userDao = server.getUserDao();
		itemDao = server.getItemDao();
		shareDao = server.getShareDao();
		clientConnectionManager = server.getClientConnectionManager();
		offPacketMongoDao = server.getOffPacketMongoDao();
		
		
	}

	public void route(ClientConnection fromConn, SystemPacket packet) {
		switch ( packet.getCmd() ) {
		
		case SystemPacket.NOTIFY_CACHE_EVICT:
			qvict(packet);
			break;
		case SystemPacket.NOTIFY_ITEM_DES:
//			itemdes(packet);
			break;
		case SystemPacket.NOTIFY_ITEM_NOTE://心得
			itemnote(packet);
			break;
		case SystemPacket.NOTIFY_ITEM_NOTE_COMMENT://心得评论
			itemnoteComment(packet);
			break;
		case SystemPacket.NOTIFY_ITEM_NOTE_PRAISE://心得点赞
			itemnotePraise(packet);
			break;
		
		default:
			break;
		}		
	} 

	private void itemnotePraise(SystemPacket packet) {
		ItemNotePraise itemNotePraise = packet.decoder(ItemNotePraise.class);
		try {
			itemNotePraise = itemNotesDao.readByCondition(ItemNotePraise.class, " id=? ", itemNotePraise.getId());
			if(itemNotePraise==null){
				return ;
			}
			
			//获取心得
			ItemNotes temp = itemNotesDao.findItemNotesByid(itemNotePraise.getItem_note_id());
			
			ItemNotes itemNotes = (ItemNotes) temp.clone();
			if(itemNotes==null){
				return ;
			}
			
			itemNotes.setItem_note_id(itemNotePraise.getItem_note_id());
			//首先判断点赞人
			if(itemNotes.getUser_id().equals(itemNotePraise.getUser_id())){
				return ;
			}
			
			Item item = itemDao.readByCondition(Item.class, " id = ? ", itemNotes.getItem_id());
			if(item==null){
				return ;
			}
			
			User userPraise = userDao.findUserByid(itemNotePraise.getUser_id());
			

			//首先判断这个指数的权限
			if(item.getShow_note()==null){
				item.setShow_note(true);
			}
			
			String share_oitemid = item.getId();
			
			String text_itemString = null;
			if(Constant.DATA_SOURCE_SHARE.equals(item.getData_source())){
				Item original_item = itemDao.findItemByid(item.getOriginal_item_id());
				text_itemString = original_item.getAttrs();
				
				if(original_item.getShow_note()==null){
					original_item.setShow_note(true);
				}
				
				share_oitemid = original_item.getId();
				
				if(!original_item.getShow_note()){
					return ;
				}
				
			}else{
				text_itemString = item.getAttrs();
				
				if(!item.getShow_note()){
					return ;
				}
			}
			
			if(!StringUtils.isBlank(text_itemString)){
				try {
					ItemAttrs itemAttrs = JSON.parseObject(text_itemString, ItemAttrs.class);
					itemNotes.setTextItem(itemAttrs.isTextItem());
				} catch (Exception e) {
				}
			}
			
			itemNotes.setItem_name(item.getItem_name());
			itemNotes.setHead_pic(userPraise.getHead_pic());
			itemNotes.setUser_name(userPraise.getName());
			
			itemNotes.setCreater_at(itemNotePraise.getCreater_at());
			if(itemNotes.getContent()!=null && itemNotes.getContent().length()>20){
				itemNotes.setContent(itemNotes.getContent().substring(0, 20));
			}
			
			Share shareForm = new Share();
			shareForm.setSource_id(share_oitemid);
			shareForm.setSource_type(1);
			List<Share> listShare = shareDao.findShareList(shareForm);
			if(listShare==null){
				return ;
			}
			if(listShare.size()==0){
				return ;
			}
			User shareuser = userDao.findUserByid(item.getUser_id());
			//组装发送人员名单
			Set<String> userSet = new HashSet<String>();
			Map<String, String> usersw = new HashMap<String, String>();
			Map<String, String> usershareid = new HashMap<String, String>();
			Map<String, String> useritemid = new HashMap<String, String>();
			for(Share share : listShare){
				shareuser = userDao.findUserByid(share.getUser_id());
				userSet.add(shareuser.getId());
				usersw.put(shareuser.getId(), shareuser.getSwitchboard_id());
				usershareid.put(shareuser.getId(), share.getId());
				useritemid.put(shareuser.getId(), share.getItem_id());
				
			}
			
			GroupMsgPacket groupMsgPacket = ServerPacketFactory.createGroupMessagePacket("1"); 
			groupMsgPacket.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			groupMsgPacket.setCmd(GroupMsgPacket.CMD_ITEM_NOTE_PRAISE);
					
			//删除共享着自己
			userSet.remove(userPraise.getId());
			
			
			String to = itemNotes.getUser_id() ;
			itemNotes.setBelong_to(to);
			itemNotes.setUser_id(to);
			itemNotes.setItem_id(useritemid.get(to));
			itemNotes.setShareid(usershareid.get(to));
			
			itemNotes.setUser_id(userPraise.getId());
			groupMsgPacket.setTo(to);
			groupMsgPacket.setBody(JSON.toJSONString(itemNotes));
		
			ClientConnection clientConnection = clientConnectionManager.getAuthConnection( to );
			if(clientConnection==null){
				offPacketMongoDao.insert(usersw.get(to),
						PacketUtil.cloneOffPacket(groupMsgPacket, to, null ));
				DoeisJPush.sendNotification(to, userPraise.getName()+ "赞了您的心得");
				
			}else{
				clientConnection.deliver(groupMsgPacket);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void itemnoteComment(SystemPacket packet) {
		
		try{
			ItemNoteComment itemNoteComment = packet.decoder(ItemNoteComment.class);
			
			itemNoteComment = itemNotesDao.readByCondition(ItemNoteComment.class, " id=? ", itemNoteComment.getId());
			if(itemNoteComment==null){
				return ;
			}
			
			//获取心得
			ItemNotes itemNotes = itemNotesDao.findItemNotesByid(itemNoteComment.getItem_note_id());
			if(itemNotes==null){
				return ;
			}
			
			Item item = itemDao.readByCondition(Item.class, " id = ? ", itemNotes.getItem_id());
			if(item==null){
				return ;
			}
			String share_oitemid = item.getId();
			User userPraise = userDao.findUserByid(itemNoteComment.getUser_id());
			
			String text_itemString = null;
			if(Constant.DATA_SOURCE_SHARE.equals(item.getData_source())){
				Item original_item = itemDao.findItemByid(item.getOriginal_item_id());
				
				//首先判断这个指数的权限
				if(original_item.getShow_note()==null){
					original_item.setShow_note(true);
				}
				
				if(!original_item.getShow_note()){
					return ;
				}
				
				share_oitemid = original_item.getId();
				
				text_itemString = original_item.getAttrs();
				
			}else{
				text_itemString = item.getAttrs();
				
				//首先判断这个指数的权限
				if(item.getShow_note()==null){
					item.setShow_note(true);
				}
				
				if(!item.getShow_note()){
					return ;
				}
				
			}
			
			if(!StringUtils.isBlank(text_itemString)){
				try {
					ItemAttrs itemAttrs = JSON.parseObject(text_itemString, ItemAttrs.class);
					itemNoteComment.setTextItem(itemAttrs.isTextItem());
				} catch (Exception e) {
				}
			}
			
			itemNoteComment.setItem_name(item.getItem_name());
			itemNoteComment.setHead_url(userPraise.getHead_pic());
			itemNoteComment.setUser_name(userPraise.getName());
			
			Share shareForm = new Share();
			shareForm.setSource_id(share_oitemid);
			shareForm.setSource_type(1);
			List<Share> listShare = shareDao.findShareList(shareForm);
			if(listShare==null){
				return ;
			}
			if(listShare.size()==0){
				return ;
			}
			User shareuser = userDao.findUserByid(item.getUser_id());
			//组装发送人员名单
			Set<String> userSet = new HashSet<String>();
			Map<String, String> usersw = new HashMap<String, String>();
			Map<String, Share> usershareid = new HashMap<String, Share>();
			for(Share share : listShare){
				
				shareuser = userDao.findUserByid(share.getUser_id());
				if(Constant.SHARE_SCOPE_ZHIDING.equals(share.getScope())){//组内指定用户
					for(String mobile : share.getEmails().split(" ")){
						List<User> listTempUser = userDao.findUserByMobile(mobile, shareuser.getSwitchboard_id());
						if(listTempUser==null){
							continue ;
						}
						for(User user : listTempUser){
							userSet.add(user.getId());
							usersw.put(user.getId(), user.getSwitchboard_id());
							usershareid.put(user.getId(), share);
						}
					}
					
					usersw.put(shareuser.getId(), shareuser.getSwitchboard_id());
					userSet.add(shareuser.getId());
					usershareid.put(shareuser.getId(), share);
					
				}else if(Constant.SHARE_SCOPE_ZHIDING_FANGDO.equals(share.getScope()) ){//组外指定用户
					User user = null;
					for(String mobile : share.getEmails().split(" ")){
						user = userDao.findUserByLogin(mobile.trim());
						if(user==null){
							continue;
						}
						userSet.add(user.getId());
						usersw.put(user.getId(), user.getSwitchboard_id());
						usershareid.put(user.getId(), share);
					}
					
					usersw.put(shareuser.getId(), shareuser.getSwitchboard_id());
					userSet.add(shareuser.getId());
					usershareid.put(shareuser.getId(), share);
					
				}else if(Constant.SHARE_SCOPE_DEP.equals(share.getScope())){//本部门
					List<User> listUsers = userDao.findUserByDepartmentId(shareuser.getDepartment_id(), false);
					if(listUsers!=null){
						for(User user :listUsers ){
							userSet.add(user.getId());
							usershareid.put(user.getId(), share);
							usersw.put(user.getId(), user.getSwitchboard_id());
						}
					}
				}else if(Constant.SHARE_SCOPE_COMPANY.equals(share.getScope())){//本组
					List<User> listUsers = userDao.findUserBySwitchBoard(shareuser.getSwitchboard_id(), false);
					if(listUsers!=null){
						for(User user :listUsers ){
							userSet.add(user.getId());
							usershareid.put(user.getId(), share);
							usersw.put(user.getId(), user.getSwitchboard_id());
						}
					}
				}
			}
			
			//开始发送信息
			GroupMsgPacket groupMsgPacket = ServerPacketFactory.createGroupMessagePacket("1"); 
			groupMsgPacket.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			groupMsgPacket.setCmd(GroupMsgPacket.CMD_ITEM_NOTE_COMMENT);
			
			//删除共享着自己
			if(itemNoteComment.getDesignate()==null){
				userSet.remove(userPraise.getId());
			}
			
			String note_context = itemNotes.getContent();
			if("pc".equals(itemNotes.getCome_from()) && !StringUtils.isBlank(note_context)){
				note_context = note_context.replaceAll("<\\s*img\\s+([^>]*)\\s*>", " [图片] ");
				note_context = Jsoup.clean(note_context, new Whitelist());
			}
			
			if(note_context!=null && note_context.length() > 15 ){
				itemNoteComment.setNote_content(note_context.substring(0, 15)+"...");
			}else{
				itemNoteComment.setNote_content(note_context);
			}
			itemNoteComment.setNote_img(itemNotes.getImg());
			
			User user = userDao.findUserByid(itemNotes.getUser_id());
			if(user!=null){
				itemNoteComment.setCreator(user.getName());
			}
			
			String showcontext = itemNoteComment.getUser_name()+"回复了心得";
			if(itemNoteComment.getReply_id()!=null){
				user = userDao.findUserByid(itemNoteComment.getReply_id());
				if(user!=null){
					itemNoteComment.setReply_name(user.getName());
					showcontext = itemNoteComment.getUser_name()+"评论["+itemNoteComment.getReply_name()+"]:"+note_context;
				}
			}else{
				showcontext = itemNoteComment.getUser_name()+"评论["+itemNoteComment.getCreator()+"]:"+note_context;
			}
			
			ClientConnection clientConnection = null;
			
			Map<String, ClientConnection> map = clientConnectionManager.getAuthConnections();
			Set<String> offUserSet = new HashSet<String>();//需要向极光推送的用户群
			
			for(String userid : userSet ){
				itemNoteComment.setBelong_to(userid);
				itemNoteComment.setItem_id(usershareid.get(userid).getItem_id());
				itemNoteComment.setShareid(usershareid.get(userid).getId());
				groupMsgPacket.setBody(JSON.toJSONString(itemNoteComment));
				groupMsgPacket.setTo(userid);
				clientConnection = map.get( userid );
				if(clientConnection==null){
					offPacketMongoDao.insert(usersw.get(userid),
							PacketUtil.cloneOffPacket(groupMsgPacket, userid, null ));
					offUserSet.add(userid);
				}else{
					clientConnection.deliver(groupMsgPacket);
				}
			}
			
			if(offUserSet.size() > 0){
				QueueManager queueManager = server.getT(QueueManager.class);
				
				JpushBean jpushBean = new JpushBean(); 
				jpushBean.setContent(showcontext);
				jpushBean.setUseridSet(offUserSet);
				if(queueManager==null){
					DoeisJPushWithAlias.sendNotificationSet(jpushBean.getUseridSet(),
							jpushBean.getContent());
				}else{
					queueManager.sendJpush(jpushBean);	
				}
			}
			
		}catch(Exception e){
			e.printStackTrace(); 
		}
	}
	
	private void itemnote(SystemPacket packet) {
		long start = System.currentTimeMillis();
		ItemNotes itemNotes = packet.decoder(ItemNotes.class);
		try {
			itemNotes = itemNotesDao.readByCondition(ItemNotes.class, " id = ? ", itemNotes.getId());
					
			if(itemNotes==null){
				return ;
			}
			User itemuser = userDao.findUserByid(itemNotes.getUser_id());
			itemNotes.setUser_name(itemuser.getName());
			
			Item item = itemDao.readByCondition(Item.class, " id = ? ", itemNotes.getItem_id());
			if(item==null){
				return ;
			}
			
			String text_itemString = null;
			if(Constant.DATA_SOURCE_SHARE.equals(item.getData_source())){
				Item original_item = itemDao.findItemByid(item.getOriginal_item_id());
				text_itemString = original_item.getAttrs();
			}else{
				text_itemString = item.getAttrs();
			}
			
			if(!StringUtils.isBlank(text_itemString)){
				try {
					ItemAttrs itemAttrs = JSON.parseObject(text_itemString, ItemAttrs.class);
					itemNotes.setTextItem(itemAttrs.isTextItem());
				} catch (Exception e) {
				}
			}
			
			itemNotes.setItem_name(item.getItem_name());
			itemNotes.setHead_pic(itemuser.getHead_pic());
			//首先判断这个指数的权限
			if(item.getShow_note()==null){
				item.setShow_note(true);
			}
			
			if(!item.getShow_note()){
				return ;
			}
			
			Share shareForm = new Share();
			shareForm.setSource_id(itemNotes.getItem_id());
			shareForm.setSource_type(1);
			List<Share> listShare = shareDao.findShareList(shareForm);
			if(listShare==null){
				return ;
			}
			if(listShare.size()==0){
				return ;
			}
			
			User shareuser = null ;
			//组装发送人员名单
			Set<String> userSet = new HashSet<String>();
			Map<String, String> usersw = new HashMap<String, String>();
			Map<String, Share> usershareid = new HashMap<String, Share>();
			for(Share share : listShare){
				
				shareuser = userDao.findUserByid(share.getUser_id());
				if(!userSet.contains(shareuser.getId())){
					userSet.add(shareuser.getId());
					usersw.put(shareuser.getId(), shareuser.getSwitchboard_id());
					usershareid.put(shareuser.getId(), share);
				}
				
				if(Constant.SHARE_SCOPE_ZHIDING.equals(share.getScope())){//组内指定用户
					StringBuffer sql = new StringBuffer("select * from user where mobile in ( ");
					for(String mobile : share.getEmails().split(" ")){
						sql.append("'"+mobile+"',");
					}
					sql.append("-1) and  switchboard_id = ? ");
					List<User> listTempUser = userDao.query(User.class, sql.toString(), false, itemuser.getSwitchboard_id());
					if(listTempUser==null){
						continue ;
					}
					for(User user : listTempUser){
						userSet.add(user.getId());
						usersw.put(user.getId(), user.getSwitchboard_id());
						usershareid.put(user.getId(), share);
					}
					
				}else if(Constant.SHARE_SCOPE_ZHIDING_FANGDO.equals(share.getScope()) ){//组外指定用户
					User user = null;
					for(String mobile : share.getEmails().split(" ")){
						user = userDao.findUserByLogin(mobile.trim());
						if(user==null){
							continue;
						}
						userSet.add(user.getId());
						usersw.put(user.getId(), user.getSwitchboard_id());
						usershareid.put(user.getId(), share);
					}
				}else if(Constant.SHARE_SCOPE_DEP.equals(share.getScope())){//本部门
					List<User> listUsers = userDao.findUserByDepartmentId(shareuser.getDepartment_id(), false);
					if(listUsers!=null){
						for(User user :listUsers ){
							userSet.add(user.getId());
							usersw.put(user.getId(), user.getSwitchboard_id());
							usershareid.put(user.getId(), share);
						}
					}
				}else if(Constant.SHARE_SCOPE_COMPANY.equals(share.getScope())){//本组
					List<User> listUsers = userDao.findUserBySwitchBoard(shareuser.getSwitchboard_id(), false);
					if(listUsers!=null){
						for(User user :listUsers ){
							userSet.add(user.getId());
							usersw.put(user.getId(), user.getSwitchboard_id());
							usershareid.put(user.getId(), share);
						}
					}
				}
			}
			
			//开始发送信息
			GroupMsgPacket groupMsgPacket = ServerPacketFactory.createGroupMessagePacket("1"); 
			groupMsgPacket.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			groupMsgPacket.setCmd(GroupMsgPacket.CMD_ITEM_NOTE);
			
			//删除共享着自己
			if(StringUtils.isBlank(itemNotes.getDesignate())){
				userSet.remove(itemuser.getId());
			}
			
			ItemNotes sendNote = (ItemNotes) itemNotes.clone() ;
			if("pc".equals(itemNotes.getCome_from())){
				String note_context = itemNotes.getContent();
				if(!StringUtils.isBlank(note_context)){
					note_context = note_context.replaceAll("<\\s*img\\s+([^>]*)\\s*>", " [图片] ");
					note_context = Jsoup.clean(note_context, new Whitelist());
				}
				sendNote.setContent(note_context);
			}
			
			ClientConnection clientConnection = null;
			Map<String, ClientConnection> map = clientConnectionManager.getAuthConnections();
			
			Share tempShare = null;
			
			String offlineContext = itemuser.getName()+ "更新了心得";
			if(!StringUtils.isBlank(itemNotes.getContent())){//心得内容不是空
				if(itemNotes.getContent().length() > 15){
					offlineContext = itemuser.getName()+ "新心得："+itemNotes.getContent().substring(0, 15)+"...";
				}else{
					offlineContext = itemuser.getName()+ "新心得："+itemNotes.getContent();
				}
			}else{
				//查看是否有图片
				if(!StringUtils.isBlank(itemNotes.getImg())){
					offlineContext = itemuser.getName()+ "新心得：[图片]";
				}
			}
			
			Set<String> offUserSet = new HashSet<String>();//需要向极光推送的用户群
			
			for(String userid : userSet ){
				tempShare = usershareid.get(userid);
				if(userid.equals(itemuser.getId())){//心得创建者itemid发送共享之前的
					sendNote.setItem_id(item.getId());
				}else{
					sendNote.setItem_id(tempShare.getItem_id());
				}
				
				sendNote.setShareid(tempShare.getId());
				sendNote.setHead_pic(tempShare.getHead_pic());
				groupMsgPacket.setBody(JSON.toJSONString(sendNote));
				groupMsgPacket.setTo(userid);
				clientConnection = map.get( userid );
				if(clientConnection==null){
					offPacketMongoDao.insert(usersw.get(userid),
							PacketUtil.cloneOffPacket(groupMsgPacket, userid, null ));
					offUserSet.add(userid);
				}else{
					clientConnection.deliver(groupMsgPacket);
				}
			}
			
			if(offUserSet.size() > 0){
				QueueManager queueManager = server.getT(QueueManager.class);
				
				JpushBean jpushBean = new JpushBean(); 
				jpushBean.setContent(offlineContext);
				jpushBean.setUseridSet(offUserSet);
				System.err.println(""+offUserSet.size()+"  "+queueManager);
				if(queueManager==null){
					DoeisJPushWithAlias.sendNotificationSet(jpushBean.getUseridSet(),
							jpushBean.getContent());
				}else{
					queueManager.sendJpush(jpushBean);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.err.println((System.currentTimeMillis()-start) + "   ||   " + itemNotes.getId() );
	}
	
	private void qvict(SystemPacket packet) {
//		ShareDao shareDao = new ShareDao();
//		try {
//			Share share = shareDao.findShareByid("ff8081814ccb212b014ccc95374502fa");
			CacheBean cacheBean = packet.decoder(CacheBean.class);
			CacheManager.evict(cacheBean.getName(), cacheBean.getKey());
//			share = shareDao.findShareByid("ff8081814ccb212b014ccc95374502fa");
//		} catch (DaoException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
	}
	
	

}
